import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { toast } from '@/lib/toast-with-audio';
import { useAuth } from '@/contexts/authContext';
import { useTheme } from '@/hooks/useTheme';

export default function Register() {
  const [formData, setFormData] = useState({
    username: '',
    password: '',
    confirmPassword: '',
    name: '',
    email: '',
    phone: '',
    department: '',
    position: ''
  });
  const [validationErrors, setValidationErrors] = useState({
    confirmPassword: '',
    email: '',
    phone: ''
  });
  const [isLoading, setIsLoading] = useState(false);
  const navigate = useNavigate();
  const { register } = useAuth();
  const { isDark } = useTheme();

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const validateConfirmPassword = () => {
    if (formData.confirmPassword && formData.password !== formData.confirmPassword) {
      setValidationErrors(prev => ({
        ...prev,
        confirmPassword: '两次输入的密码不一致'
      }));
    } else {
      setValidationErrors(prev => ({
        ...prev,
        confirmPassword: ''
      }));
    }
  };

  const validateEmail = () => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (formData.email && !emailRegex.test(formData.email)) {
      setValidationErrors(prev => ({
        ...prev,
        email: '请输入有效的邮箱地址'
      }));
    } else {
      setValidationErrors(prev => ({
        ...prev,
        email: ''
      }));
    }
  };

  const validatePhone = () => {
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!formData.phone.trim()) {
      setValidationErrors(prev => ({
        ...prev,
        phone: '手机号码为必填项'
      }));
    } else if (!phoneRegex.test(formData.phone)) {
      setValidationErrors(prev => ({
        ...prev,
        phone: '请输入有效的手机号码'
      }));
    } else {
      setValidationErrors(prev => ({
        ...prev,
        phone: ''
      }));
    }
  };

  const handleBlur = (e: React.FocusEvent<HTMLInputElement>) => {
    const { name } = e.target;
    if (name === 'confirmPassword') {
      validateConfirmPassword();
    } else if (name === 'email') {
      validateEmail();
    } else if (name === 'phone') {
      validatePhone();
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // 执行所有验证
    validateConfirmPassword();
    validateEmail();
    validatePhone();
    
    // 检查是否有验证错误
    if (validationErrors.confirmPassword || validationErrors.email || validationErrors.phone) {
      toast.error('请修正表单中的错误');
      return;
    }
    
    // 表单验证
    if (!formData.username.trim() || !formData.password.trim()) {
      toast.error('请输入用户名和密码');
      return;
    }

    if (formData.password !== formData.confirmPassword) {
      toast.error('两次输入的密码不一致');
      return;
    }

    if (formData.password.length < 6) {
      toast.error('密码长度不能少于6位');
      return;
    }

    if (!formData.name.trim()) {
      toast.error('请输入真实姓名');
      return;
    }

    if (!formData.email.trim()) {
      toast.error('请输入邮箱地址');
      return;
    }

    if (!formData.phone.trim()) {
      toast.error('请输入手机号码');
      return;
    }

    setIsLoading(true);

    try {
      const success = await register(formData);
      
      if (success) {
        toast.success('注册申请已提交，请等待管理员审核');
        navigate('/login');
      } else {
        toast.error('注册失败，请重试');
      }
    } catch (error) {
      toast.error('注册失败，请重试');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className={`min-h-screen flex ${isDark ? 'bg-gray-900' : 'bg-gray-50'}`}>
      {/* 左侧背景区域 */}
      <div className="hidden lg:flex lg:w-1/2 bg-gradient-to-br from-blue-600 to-blue-800 relative overflow-hidden">
        {/* 背景装饰 */}
        <div className="absolute inset-0 bg-black/10"></div>
        
        {/* 主要内容 */}
        <div className="relative z-10 flex flex-col justify-center px-12">
          <div className="max-w-md">
            {/* 品牌区域 */}
            <div className="mb-16">
              <div className="flex items-center mb-8">
                <div className="w-14 h-14 bg-white/20 backdrop-blur-sm rounded-xl flex items-center justify-center mr-4">
                  <svg className="w-9 h-9 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4" />
                  </svg>
                </div>
                <div>
                  <h1 className="text-6xl font-bold text-white">Astra-plm</h1>
                  <p className="text-blue-100 text-2xl mt-2 font-bold">统一管理后台</p>
                </div>
              </div>
            
              <p className="text-blue-100 text-lg font-bold leading-relaxed">
                &nbsp;
              </p>
            </div>

            {/* 特性展示 */}
            <div className="space-y-12">
              <div className="flex items-start">
                <div className="w-12 h-12 bg-white/10 backdrop-blur-sm rounded-lg flex items-center justify-center mr-4 flex-shrink-0">
                  <svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
                  </svg>
                </div>
                <div>
                  <h3 className="text-white font-semibold mb-1">快速注册，便捷使用</h3>
                  <p className="text-blue-100 text-sm">简单几步完成注册，享受专业的管理服务</p>
                </div>
              </div>
              
              <div className="flex items-start">
                <div className="w-12 h-12 bg-white/10 backdrop-blur-sm rounded-lg flex items-center justify-center mr-4 flex-shrink-0">
                  <svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
                  </svg>
                </div>
                <div>
                  <h3 className="text-white font-semibold mb-1">安全审核机制</h3>
                  <p className="text-blue-100 text-sm">管理员审核确保系统安全，保护企业数据</p>
                </div>
              </div>
              
              <div className="flex items-start">
                <div className="w-12 h-12 bg-white/10 backdrop-blur-sm rounded-lg flex items-center justify-center mr-4 flex-shrink-0">
                  <svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
                  </svg>
                </div>
                <div>
                  <h3 className="text-white font-semibold mb-1">专业团队支持</h3>
                  <p className="text-blue-100 text-sm">专业的技术团队为您提供全方位的技术支持</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 右侧注册区域 */}
      <div className="flex-1 flex items-center justify-center px-4 py-12 sm:px-6 lg:px-8">
        <div className="max-w-md w-full space-y-8">
          <div className="text-center">
            <h2 className="text-3xl font-bold text-gray-900 dark:text-white">
              用户注册
            </h2>
            <p className="mt-2 text-sm text-gray-600 dark:text-gray-400">
              创建您的账户，开始使用系统
            </p>
          </div>

          <form className="mt-8 space-y-6" onSubmit={handleSubmit}>
            <div className="space-y-4">
              <div>
                <label htmlFor="username" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  用户名 *
                </label>
                <input
                  id="username"
                  name="username"
                  type="text"
                  required
                  className="relative block w-full px-3 py-3 border border-gray-300 dark:border-gray-600 placeholder-gray-500 dark:placeholder-gray-400 text-gray-900 dark:text-white rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white dark:bg-gray-800 transition-colors"
                  placeholder="请输入用户名"
                  value={formData.username}
                  onChange={handleChange}
                />
              </div>
              
              <div>
                <label htmlFor="password" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  密码 *
                </label>
                <input
                  id="password"
                  name="password"
                  type="password"
                  required
                  className="relative block w-full px-3 py-3 border border-gray-300 dark:border-gray-600 placeholder-gray-500 dark:placeholder-gray-400 text-gray-900 dark:text-white rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white dark:bg-gray-800 transition-colors"
                  placeholder="请输入密码（至少6位）"
                  value={formData.password}
                  onChange={handleChange}
                />
              </div>

              <div>
                <label htmlFor="confirmPassword" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  确认密码 *
                </label>
                <input
                  id="confirmPassword"
                  name="confirmPassword"
                  type="password"
                  required
                  className={`relative block w-full px-3 py-3 border ${
                    validationErrors.confirmPassword 
                      ? 'border-red-500 focus:border-red-500 focus:ring-red-500' 
                      : 'border-gray-300 dark:border-gray-600 focus:ring-blue-500 focus:border-transparent'
                  } placeholder-gray-500 dark:placeholder-gray-400 text-gray-900 dark:text-white rounded-lg focus:outline-none focus:ring-2 bg-white dark:bg-gray-800 transition-colors`}
                  placeholder="请再次输入密码"
                  value={formData.confirmPassword}
                  onChange={handleChange}
                  onBlur={handleBlur}
                />
                {validationErrors.confirmPassword && (
                  <p className="mt-1 text-sm text-red-600 dark:text-red-400">
                    {validationErrors.confirmPassword}
                  </p>
                )}
              </div>

              <div>
                <label htmlFor="name" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  真实姓名 *
                </label>
                <input
                  id="name"
                  name="name"
                  type="text"
                  required
                  className="relative block w-full px-3 py-3 border border-gray-300 dark:border-gray-600 placeholder-gray-500 dark:placeholder-gray-400 text-gray-900 dark:text-white rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white dark:bg-gray-800 transition-colors"
                  placeholder="请输入真实姓名"
                  value={formData.name}
                  onChange={handleChange}
                />
              </div>

              <div>
                <label htmlFor="email" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  邮箱地址 *
                </label>
                <input
                  id="email"
                  name="email"
                  type="email"
                  required
                  className={`relative block w-full px-3 py-3 border ${
                    validationErrors.email 
                      ? 'border-red-500 focus:border-red-500 focus:ring-red-500' 
                      : 'border-gray-300 dark:border-gray-600 focus:ring-blue-500 focus:border-transparent'
                  } placeholder-gray-500 dark:placeholder-gray-400 text-gray-900 dark:text-white rounded-lg focus:outline-none focus:ring-2 bg-white dark:bg-gray-800 transition-colors`}
                  placeholder="请输入邮箱地址"
                  value={formData.email}
                  onChange={handleChange}
                  onBlur={handleBlur}
                />
                {validationErrors.email && (
                  <p className="mt-1 text-sm text-red-600 dark:text-red-400">
                    {validationErrors.email}
                  </p>
                )}
              </div>

              <div>
                <label htmlFor="phone" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  手机号码 *
                </label>
                <input
                  id="phone"
                  name="phone"
                  type="tel"
                  required
                  className={`relative block w-full px-3 py-3 border ${
                    validationErrors.phone 
                      ? 'border-red-500 focus:border-red-500 focus:ring-red-500' 
                      : 'border-gray-300 dark:border-gray-600 focus:ring-blue-500 focus:border-transparent'
                  } placeholder-gray-500 dark:placeholder-gray-400 text-gray-900 dark:text-white rounded-lg focus:outline-none focus:ring-2 bg-white dark:bg-gray-800 transition-colors`}
                  placeholder="请输入手机号码"
                  value={formData.phone}
                  onChange={handleChange}
                  onBlur={handleBlur}
                />
                {validationErrors.phone && (
                  <p className="mt-1 text-sm text-red-600 dark:text-red-400">
                    {validationErrors.phone}
                  </p>
                )}
              </div>

              <div>
                <label htmlFor="department" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  部门
                </label>
                <input
                  id="department"
                  name="department"
                  type="text"
                  className="relative block w-full px-3 py-3 border border-gray-300 dark:border-gray-600 placeholder-gray-500 dark:placeholder-gray-400 text-gray-900 dark:text-white rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white dark:bg-gray-800 transition-colors"
                  placeholder="请输入部门"
                  value={formData.department}
                  onChange={handleChange}
                />
              </div>

              <div>
                <label htmlFor="position" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  职位
                </label>
                <input
                  id="position"
                  name="position"
                  type="text"
                  className="relative block w-full px-3 py-3 border border-gray-300 dark:border-gray-600 placeholder-gray-500 dark:placeholder-gray-400 text-gray-900 dark:text-white rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white dark:bg-gray-800 transition-colors"
                  placeholder="请输入职位"
                  value={formData.position}
                  onChange={handleChange}
                />
              </div>
            </div>

            <div>
              <button
                type="submit"
                disabled={isLoading}
                className="group relative w-full flex justify-center py-3 px-4 border border-transparent text-sm font-medium rounded-lg text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                {isLoading ? (
                  <>
                    <svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" fill="none" viewBox="0 0 24 24">
                      <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                      <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                    注册中...
                  </>
                ) : (
                  '提交注册申请'
                )}
              </button>
            </div>

            <div className="text-center">
              <p className="text-sm text-gray-600 dark:text-gray-400">
                已有账户？{' '}
                <a 
                  href="/login" 
                  className="font-medium text-blue-600 dark:text-blue-400 hover:text-blue-500 transition-colors underline"
                >
                  立即登录
                </a>
              </p>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}